package com.dawn.socket;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class DataUtil {

	public static byte[] concatenate(byte[]... args) {
		int pos = 0;
		int len = 0;
		for (byte[] barr : args) {
			len += barr.length;
		}

		byte[] ret = new byte[len];

		for (byte[] barr : args) {
			System.arraycopy(barr, 0, ret, pos, barr.length);
			pos += barr.length;
		}

		return ret;
	}

	public static byte[] byteFormat(int value) {
		byte[] b = new byte[4];

		b[0] = (byte) (value >> (8 * 0));
		b[1] = (byte) (value >> (8 * 1));
		b[2] = (byte) (value >> (8 * 2));
		b[3] = (byte) (value >> (8 * 3));

		return b;
	}

	public static byte[] byteFormat(String value, int length) {

		// return value.getBytes();
		Charset charset = null;
		CharsetEncoder encoder = null;
		CharBuffer cb = CharBuffer.wrap(value.toCharArray());
		ByteBuffer re = null;
		try {
			charset = Charset.forName("gb2312");
			encoder = charset.newEncoder();
			re = encoder.encode(cb);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return byteFormat(re.array(), length);
	}

	public static byte[] byteFormat(byte[] value, int length) {
		byte[] b = new byte[length];

		for (int i = 0; i < length; i++) {
			if (i < value.length) {
				b[i] = value[i];
			} else {
				b[i] = 0;
			}
		}
		return b;
	}

	public static int readInt(ByteBuffer bb, int start) {

		int ret = 0;
		for (int i = start; i < start + 4; i++) {
			ret += bb.get(i) << (8 * (i - start));
		}

		return ret;
	}

	public static String readString(ByteBuffer bb) {

		bb.flip();
		Charset charset = null;
		CharsetDecoder decoder = null;
		CharBuffer charBuffer = null;
		try {
			charset = Charset.forName("gb2312");
			decoder = charset.newDecoder();
			charBuffer = decoder.decode(bb);
			return charBuffer.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
	}

	public static String readCharString(ByteBuffer bb) {

		char[] c = new char[bb.capacity()];
		for (int i = 0; i < bb.capacity(); i++) {
			byte tmp = bb.get(i);
			c[i ] = (char) tmp;
		}
		return String.valueOf(c);
	}

	public static void print(byte[] ba) {

		for (int i = 0; i < ba.length; i++) {
			System.out.print(ba[i]);
			System.out.print(".");
		}
		System.out.println();
	}

	public static void print(ByteBuffer ba) {
		print(ba.array());
	}
}
